﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Data.DataSetGenerator
{
    public class SqlDataSetReverseEngineer
    {
        public static DataSetDescriptor Process(DataSet dataSet)
        {
            DataSetDescriptor descriptor = new DataSetDescriptor();
            descriptor.DataSetName = dataSet.DataSetName;

            SqlTypedDataSetGenerator generator = new SqlTypedDataSetGenerator(descriptor);

            foreach (DataTable dataTable in dataSet.Tables)
            {
                TableDescriptor tableDescriptor = new TableDescriptor();
                tableDescriptor.TableName = dataTable.TableName;
                tableDescriptor.Action = SchemaObjectActionEnum.Add;
                tableDescriptor.Source = dataTable.TableName;
                descriptor.Tables.Add(tableDescriptor);
            }

            foreach (DataRelation relation in dataSet.Relations)
            {
                RelationDescriptor relationDescriptor = new RelationDescriptor();
                relationDescriptor.RelationName = relation.RelationName;
                relationDescriptor.PKDataTable = relation.ParentTable.TableName;

                var pkColumns = relation.ParentColumns.Select(col => col.ColumnName).ToArray();
                var pkColumnNames = String.Join(", ", pkColumns);
                relationDescriptor.PKDataColumns = pkColumnNames;

                relationDescriptor.FKDataTable = relation.ChildTable.TableName;

                var fkColumns = relation.ChildColumns.Select(col => col.ColumnName).ToArray();
                var fkColumnNames = String.Join(", ", fkColumns);

                relationDescriptor.FKDataColumns = fkColumnNames;

                descriptor.Relations.Add(relationDescriptor);    
            }

            return descriptor;
        }
    }
}
